package com.goodfox.web.biz.forest.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.biz.forest.entity.ForestRights;
import com.goodfox.web.biz.forest.entity.Woodland;
import com.goodfox.web.biz.forest.entity.WoodlandFour;
import com.goodfox.web.biz.forest.service.ForestRightsService;
import com.goodfox.web.biz.forest.service.WoodlandService;
import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.area.service.AreaService;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.file.entity.WebFormEntity;
import com.goodfox.web.generic.file.service.FileUploadService;
import com.goodfox.web.generic.provide.entity.Pager;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.service.ExcelTemplateService;
import com.goodfox.web.generic.provide.util.AttributeUtil;
import com.goodfox.web.generic.provide.util.DateUtil;
import com.goodfox.web.generic.provide.util.ParameterUtil;

/**
 * 林权证Controller
 * @author bow
 *
 */
@Controller
@RequestMapping("/rights")
public class ForestRightsController {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(ForestRightsController.class);
	
	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;

	/** 林权证Service */
	@Autowired
	private ForestRightsService forestRightsService;

	/** 林地Service */
	@Autowired
	private WoodlandService woodlandService;
	
	/** 文件上传Service */
	@Autowired
	private FileUploadService fileUploadService;

	/** 地区Service */
	@Autowired
	private AreaService areaService;
	
	/** 导出Service */
	@Autowired
	private ExcelTemplateService excelTemplateService;

	/**
	 * 进入林权证管理首页
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsIndex.shtml")
	public String goRightstIndex(HttpServletRequest request,ModelMap model){
		logger.info("进入林权证管理首页");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
		    //当前页
			int currentPage=1;
			if(!ParameterUtil.getReqParaValue(request,"pageNum").equals("")){
				currentPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"pageNum"));
			}
			//每页多少条
			int numPerPage=15;
			if(!ParameterUtil.getReqParaValue(request,"numPerPage").equals("")){
				numPerPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"numPerPage"));
			}
			//查询条件
		    Map queryMap=entityService.fillQueryMap(request,model);
		    if(queryMap.get("affDate")!=null && !String.valueOf(queryMap.get("affDate")).equals("")){
			    queryMap.put("affDate",DateUtil.dateFormat(String.valueOf(queryMap.get("affDate")),"yyyy"));
		    }
		    if(queryMap.get("areaId")!=null && !String.valueOf(queryMap.get("areaId")).equals("")){
		    	queryMap.put("areaId", "'"+String.valueOf(queryMap.get("areaId")).replace(",", "','")+"'");
		    }
		    
		    logger.debug("areaId:"+queryMap.get("areaId"));
			Pager<ForestRights> pager=forestRightsService.queryForestRightsPager(currentPage, numPerPage, queryMap);
			model.put("rightsList", pager.getEntityList());
			Map sumMap=forestRightsService.queryForestRightsSimpleSummary(queryMap);
			Long woodlandCount=0L;
			Double acreageTotal=0.0;
			if(sumMap!=null){
				if(sumMap.get("WOODLAND_COUNT")!=null){
					woodlandCount=Long.valueOf(sumMap.get("WOODLAND_COUNT").toString());
				}
				if(sumMap.get("ACREAGE_TOTAL")!=null){
					acreageTotal=Double.valueOf(sumMap.get("ACREAGE_TOTAL").toString());
				}
			}
			model.put("woodlandCount", woodlandCount);
			model.put("acreageTotal", acreageTotal);
			
			model.put("totalCount", pager.getAllCount());
			model.put("currentPage", currentPage);
			model.put("numPerPage", numPerPage);

			model.put("rstTypeList", AttributeUtil.queryAttrListByType("登记类型"));
			model.put("fstOwnList", AttributeUtil.queryAttrListByType("林地所有权权利人"));
			model.put("speciesList", AttributeUtil.queryAttrListByType("主要树种"));
			model.put("landTypeList", AttributeUtil.queryAttrListByType("地类"));
			model.put("fstTypeList", AttributeUtil.queryAttrListByType("森林分类"));
			model.put("fstSpeciesList", AttributeUtil.queryAttrListByType("林种"));
			
			model.put("areaTopMap", areaService.querySubAreaList(new HashMap()));
			
			return "rights/rightsIndex";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入地区查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goAreaLookup.shtml")
	public String goAreaLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入地区查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "area/areaLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入多地区查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goAreaMultiLookup.shtml")
	public String goAreaMultiLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入地区查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "area/areaMultiLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入添加林权证页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsAdd.shtml")
	public String goRightsAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入添加林权证页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("rstTypeList", AttributeUtil.queryAttrListByType("登记类型"));
			model.put("fstOwnList", AttributeUtil.queryAttrListByType("林地所有权权利人"));
			model.put("speciesList", AttributeUtil.queryAttrListByType("主要树种"));
			model.put("landTypeList", AttributeUtil.queryAttrListByType("地类"));
			model.put("fstTypeList", AttributeUtil.queryAttrListByType("森林分类"));
			model.put("fstSpeciesList", AttributeUtil.queryAttrListByType("林种"));
	    	return "rights/rightsAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行林权证新增
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="rightsAdd.shtml")
	@ResponseBody
	public Map rightsAdd(HttpServletRequest request){
		logger.debug("执行林权证新增");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "rightsHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "closeCurrent");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				ForestRights entity=(ForestRights)entityService.fillEntity(request,ForestRights.class);
				forestRightsService.addForestRights(entity, request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="新增成功！";
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("rightsAdd异常：",ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入更新林权证页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsModify.shtml")
	public String goRightsModify(HttpServletRequest request,ModelMap model){
		logger.info("进入更新林权证页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("rstTypeList", AttributeUtil.queryAttrListByType("登记类型"));
			model.put("fstOwnList", AttributeUtil.queryAttrListByType("林地所有权权利人"));
			model.put("speciesList", AttributeUtil.queryAttrListByType("主要树种"));
			model.put("landTypeList", AttributeUtil.queryAttrListByType("地类"));
			model.put("fstTypeList", AttributeUtil.queryAttrListByType("森林分类"));
			model.put("fstSpeciesList", AttributeUtil.queryAttrListByType("林种"));
			model.put("rights", forestRightsService.getForestRights(ParameterUtil.getReqParaValue(request, "fstRigId")));
	    	return "rights/rightsModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行林权证更新
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="rightsModify.shtml")
	@ResponseBody
	public Map rightsModify(HttpServletRequest request){
		logger.debug("执行林权证更新");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "rightsHome");
		rspMap.put("callbackType", "update");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				ForestRights newEny=(ForestRights)entityService.fillEntity(request,ForestRights.class);
				ForestRights oldEny=forestRightsService.getForestRights(newEny.getFstRigId());
				forestRightsService.modifyForestRights(oldEny, newEny, request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("rightsModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行林权证移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="rightsRemove.shtml")
	@ResponseBody
	public Map rightsRemove(HttpServletRequest request){
		logger.debug("执行林权证移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				ForestRights entity=forestRightsService.getForestRights(ParameterUtil.getReqParaValue(request, "fstRigId"));
				forestRightsService.removeForestRights(entity, request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="移除成功！";
			}catch(Exception ex){
				logger.error("rightsRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行林权证批量移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="rightsRemoveBat.shtml")
	@ResponseBody
	public Map rightsRemoveBat(HttpServletRequest request){
		logger.debug("执行林权证批量移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				message="";
				String[] fstRigIdIds=request.getParameterValues("fstRigIdIds");
				for(String fstRigIdId:fstRigIdIds){
					ForestRights entity=forestRightsService.getForestRights(fstRigIdId);
					forestRightsService.removeForestRights(entity, request.getSession().getAttribute("loginLogId").toString());
					message+=entity.getRigCode()+"移除成功！ ";
				}
				statusCode="200";
			}catch(Exception ex){
				logger.error("rightsRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入查看林权证页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsDetail.shtml")
	public String goRightsDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入查看林权证页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("rights", forestRightsService.getForestRights(ParameterUtil.getReqParaValue(request, "fstRigId")));
	    	return "rights/rightsDetail";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入打印预览林权证页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsPrint.shtml")
	public String goRightsPrint(HttpServletRequest request,ModelMap model){
		logger.info("进入打印预览林权证页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("rights", forestRightsService.getForestRights(ParameterUtil.getReqParaValue(request, "fstRigId")));
	    	return "rights/rightsPrint";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行林地四至批量移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="fourRemoveBat.shtml")
	@ResponseBody
	public Map fourRemoveBat(HttpServletRequest request){
		logger.debug("执行林地四至批量移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "rightsHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="移除失败！";
		try{
			message="";
			String[] fourIds=request.getParameterValues("fourIds");
			for(String fourId:fourIds){
				WoodlandFour entity=woodlandService.getWoodlandFour(fourId);
				woodlandService.removeWoodlandFour(entity, request.getSession().getAttribute("loginLogId").toString());
				message+=entity.getFourName()+"移除成功！ ";
			}
			statusCode="200";
		}catch(Exception ex){
			logger.error("rightsRemove异常：",ex);
			message="移除失败:发生异常！";
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行林权证照片批量移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="photoRemoveBat.shtml")
	@ResponseBody
	public Map photoRemoveBat(HttpServletRequest request){
		logger.debug("执行林权证照片批量移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "rightsHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="移除失败！";
		try{
			message="";
			String[] photoIdPaths=request.getParameterValues("photoIdPaths");
			for(String photoIdPath:photoIdPaths){
				woodlandService.autoRemoveWoodlandPhoto(photoIdPath, request.getSession());
				message+="照片移除成功！ ";
			}
			statusCode="200";
		}catch(Exception ex){
			logger.error("rightsRemove异常：",ex);
			message="移除失败:发生异常！";
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("rightsRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入添加林权证照片页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goRightsPhotoAdd.shtml")
	public String goRightsPhotoAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入添加林权证照片页面");
		model.put("tabIndex", ParameterUtil.getReqParaValue(request, "tabIndex"));
	    return "rights/rightsPhotoAdd";
	}
	
	/**
	 * 添加林权证照片上传
	 * @return 目标页面
	 */
	@RequestMapping(value="rightsPhotoUpload.shtml")
	public void rightsPhotoUpload(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		logger.info("添加林权证照片上传");
		try{
			WebFormEntity webFormEntity=fileUploadService.webFileUpload(request, true, false, true, "rights");
			response.setContentType("text/plain");
			response.setCharacterEncoding("utf-8");
			ObjectMapper om=new ObjectMapper();
			String responseJson = om.writeValueAsString(webFormEntity);
			response.getWriter().write(responseJson);
		}catch(Exception ex){
			logger.error("rightsPhotoUpload异常：", ex);
		}
	}
	
	/**
	 * 进入林权证导入页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goImportRights.shtml")
	public String goImportRights(HttpServletRequest request,ModelMap model){
		logger.info("进入林权证导入页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "rights/rightsImport";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行林权证导入
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="importRights.shtml")
	public void importRights(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		logger.debug("执行林权证导入");
		Map rspMap = new HashMap();
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	try{
				WebFormEntity webFormEntity=fileUploadService.webFileUpload(request, true, false, false, "rights");
				Map map=forestRightsService.importForestRights(webFormEntity, request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="导入成功：共导入林权证"+map.get("rightsCount")+"个；林地"+map.get("woodCount")+"个；四至"+map.get("fourCount")+"个！";
	    	}catch(Exception ex){
	    		logger.error("importRights异常:", ex);
				message="导入失败:发生异常！";
	    	}
	    }
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("importRights rspMap:"+rspMap);
		try{
			ObjectMapper om=new ObjectMapper();
			String rspJson = om.writeValueAsString(rspMap);
			response.getWriter().write(rspJson);
			logger.debug("importRights rspJson:"+rspJson);
		}catch(Exception ex){
    		logger.error("响应信息写入异常:", ex);
    	}
		
	}
	
	/**
	 * 执行林权证导出
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value="exportRightsAll.shtml")
	public void exportRightsAll(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		logger.debug("执行林权证导出");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
		    Map queryMap=entityService.fillQueryMap(request,model);
		    if(queryMap.get("affDate")!=null && !String.valueOf(queryMap.get("affDate")).equals("")){
			    queryMap.put("affDate",DateUtil.dateFormat(String.valueOf(queryMap.get("affDate")),"yyyy"));
		    }
		    if(queryMap.get("areaId")!=null && !String.valueOf(queryMap.get("areaId")).equals("")){
		    	queryMap.put("areaId", "'"+String.valueOf(queryMap.get("areaId")).replace(",", "','")+"'");
		    }
		    List<ForestRights> entityList=forestRightsService.exportForestRightsList(request,response,queryMap);
		    excelTemplateService.webExpWorkbook(request, response, ForestRights.class, entityList);
	    }
	}
}
